package com.geekhale.validate.controller;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.util.ReflectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.validation.Errors;
import org.springframework.validation.ObjectError;
import org.springframework.validation.SmartValidator;
import org.springframework.validation.Validator;

import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;

@Component
@Slf4j
public class BaseRequestValidator implements SmartValidator {
    @Override
    public boolean supports(Class<?> clazz) {
        return true;
    }

    @Override
    public void validate(Object target, Errors errors) {
        if (target instanceof BaseRequest) {
            String validate = ((BaseRequest) target).validate();
            if (!StringUtils.isEmpty(validate)) {
                errors.reject("user", validate);
            }

            ReflectionUtils.doWithFields(target.getClass(), new ReflectionUtils.FieldCallback() {
                @Override
                public void doWith(Field field) throws IllegalArgumentException, IllegalAccessException {
                    field.setAccessible(true);
                    Object value = field.get(target);
                    validate(value, errors);
                }
            });
        }

    }

    @Override
    public void validate(Object target, Errors errors, Object... validationHints) {
        log.info("{}, {}, {}", target, errors, validationHints);
    }
}
